package com.zy.utils;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Rect;
import android.util.Log;
import android.view.View;
import android.view.ViewParent;

import com.zy.zlog.ZLog;

public class ActivityUtils {
    private static final String TAG = "ActivityUtils";


    /**
     * 返回当前屏幕是否为竖屏。
     *
     * @param context
     * @return 当且仅当当前屏幕为竖屏时返回true, 否则返回false。
     */
    public static boolean isScreenOrientationPortrait(Context context) {
        return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
    }


    public static boolean checkActivityDestroyed(Context context) {
        if (context instanceof Activity) {
            Activity activity = (Activity) context;
            if (activity.isFinishing() || activity.isDestroyed()) {
                ZLog.e(TAG, "getActivity() == null || getActivity().isFinishing() || getActivity().isDestroyed()");
                return true;
            }
        }
        return false;
    }

    public static void showViewTree(View view) {
        ZLog.d(TAG, "" + 0 + " " + view);
        ViewParent curr = view.getParent();
        int index = 1;
        while (curr != null) {
            ZLog.d(TAG, "" + index + " " + curr);
            index++;
            curr = curr.getParent();
        }
    }

    public static void showViewTreeAndLocation(View view) {
        ZLog.d(TAG, "" + 0 + " " + getVisibleRect(view) + " " + view);
        ViewParent curr = view.getParent();
        int index = 1;
        while (curr != null) {
            ZLog.d(TAG, "" + index + " " + getVisibleRect(curr) + " " + curr);
            index++;
            curr = curr.getParent();
        }
    }

    private static String getVisibleRect(ViewParent viewParent) {
        if (viewParent instanceof View) {
            return getVisibleRect((View) viewParent);
        }
        return "[]";
    }

    private static String getVisibleRect(View view) {
        Rect localVisibleRect = new Rect();
        view.getLocalVisibleRect(localVisibleRect);
        Rect globalVisibleRect = new Rect();
        view.getGlobalVisibleRect(globalVisibleRect);


        return localVisibleRect + " " + globalVisibleRect + " [" + view.getWidth() + "," + view.getHeight() + "] [" + view.getX() + "," + view.getY() + "] [" + view.getTranslationX() + "," + view.getTranslationY() + "]";
    }
}
